# coding: utf-8

# -------------------------------------------------------------------------------
# Name:         send_mail_task.py
# Description:  
# Author:       XiangjunZhao
# EMAIL:        2419352654@qq.com
# Date:         2019/11/13 9:19
# -------------------------------------------------------------------------------
import json
import logging

from celery import shared_task
from django.core.mail import EmailMessage

from apps.HttpAutoTestService.models import Parameter

logger = logging.getLogger(__name__)


@shared_task(name="发送邮件:HttpAutoTestService.send_mail_task.send_mail")
def send_mail(subject='', body='', from_email=None, to=None, bcc=None, attachments=None, headers=None, cc=None,
              reply_to=None):
    """
    发送邮件
    Args:
        subject: 主题
        body: 内容
        from_email: 发件人
        to: 收件人
        bcc: 密送
        attachments: 附件
        headers:
        cc: 抄送
        reply_to:

    Returns:

    """
    try:
        if not from_email:
            parameter = Parameter.objects.filter(key='EMAIL', is_deleted=False).first()
            if parameter:
                value = json.loads(parameter.value)
                from_email = value.get('DEFAULT_FROM_EMAIL')
        email = EmailMessage(subject=subject, body=body, from_email=from_email, to=to, bcc=bcc, attachments=attachments,
                             headers=headers, cc=cc, reply_to=reply_to)
        email.send(fail_silently=False)
    except Exception as e:
        logger.error(f'发送邮件【主题：{subject}，发件人：{from_email}，收件人：{to}，抄送：{cc}，密送：{bcc}】失败，原因：{e}')
        raise e
    else:
        logger.info(f'邮件已发送【主题：{subject}，发件人：{from_email}，收件人：{to}，抄送：{cc}，密送：{bcc}】')
